package com.dhms.uikit.select_bottom_sheet

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import com.dhms.uikit.R
import com.dhms.uikit.TitleBottomSheet
import com.dhms.uikit.databinding.FragmentSelectBottomSheetBinding

class SelectBottomSheet(
    private val itemList: List<SelectItem>,
    private val title: String?,
    private val isMultiselectMode: Boolean = true,
    val submitSelectedList: (selectedItemList: Set<SelectItem>) -> Unit
) :
    TitleBottomSheet() {

    private var _binding: FragmentSelectBottomSheetBinding? = null
    private val binding get() = _binding!!

    private val listAdapter = SelectListAdapter(isMultiselectMode) {
        submitSelectedList(it)
        super.dismiss()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSelectBottomSheetBinding.inflate(inflater, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.lifecycleOwner = viewLifecycleOwner
        binding.isMultiselectMode = isMultiselectMode

        binding.selectItemList.adapter = listAdapter
        listAdapter.submitList(itemList)
        listAdapter.notifyDataSetChanged()

        binding.submitBtn.setOnClickListener {
            submitSelectedList(listAdapter.selectedItemList)
            super.dismiss()
        }
    }

    fun setSelectedList(selectedItemList: Set<SelectItem>): SelectBottomSheet {
        listAdapter.setSelectedList(selectedItemList)

        return this
    }

    override fun show(manager: FragmentManager, tag: String?) {
        if (isAdded) {
            dismissNow()
        }
        super.show(manager, tag)
    }

    override fun getTitle(): String {
        return getString(R.string.please_select) + (title ?: "")
    }
}